#include<iostream>
#include<unistd.h>
#include<cerrno>
#include"RingQueue.hpp"
//计算器函数
const std::string ops = "+-*/%";
int calculate(int a, int b, char op)
{
    int result = 0;
    switch(op)
    {
        case '+':
            result = a + b;
            break;
        case '-':
            result = a - b;
            break;
        case '*':
            result = a * b;
            break;
        case '/':
        {
            if(b == 0)
                std::cerr << "除数不能为0\n";
            else
                result = a / b;
        }
            break;
        case '%':
        {
            if(b == 0)
                std::cerr << "取模的数字不能为0\n";
            else
                result = a % b;
        }
            break;
        default:
            break;
    }
    return result;
}

void* productor(void* arg)
{
    RingQueue<CalTask>* rq=static_cast<RingQueue<CalTask>*>(arg);
    while(true)
    {
        int x=rand()%100;
        int y=rand()%100;
        CalTask task(x,y,ops[rand()%ops.size()],calculate);
        rq->push(task);
        std::string s="生产完成,你的任务为：";
        s+=task.show_task();
        std::cout<<s<<std::endl;
    }
}
void* consumer(void* arg)
{
    RingQueue<CalTask>* rq=static_cast<RingQueue<CalTask>*>(arg);
    while(true)
    {
        CalTask task;
        rq->pop(task);
        std::string s="消费完成,你的任务为：";
        s+=task();
        std::cout<<s<<std::endl;
    }
}
int main()
{
    srand((uint64_t)time(nullptr));
    RingQueue<CalTask>* rq=new RingQueue<CalTask>(5);
    pthread_t c[3],p[5];
    for(int i=0;i<5;i++)
    pthread_create(&p[i],nullptr,productor,rq);
    for(int i=0;i<3;i++)
    pthread_create(&c[i],nullptr,consumer,rq);

    
    for(int i=0;i<5;i++)
    pthread_join(p[i],nullptr);
    for(int i=0;i<3;i++)
    pthread_join(c[i],nullptr);


    delete rq;
    return 0;
}